package com.digitalchina.lxnsy.fragment;

import android.os.Handler;
import android.os.Message;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.old.AgriculturalServiceDetailActivity;
import com.digitalchina.lxnsy.activity.old.AgriculturalServiceListActivity;
import com.digitalchina.lxnsy.activity.old.AgriculturalTrainingDetailsActivity;
import com.digitalchina.lxnsy.activity.old.AnswerListActivity;
import com.digitalchina.lxnsy.activity.old.CoinPresentListActivity;
import com.digitalchina.lxnsy.activity.old.ExpertsListActivity;
import com.digitalchina.lxnsy.activity.old.FamousInterviewActivity;
import com.digitalchina.lxnsy.activity.old.LoginGuideActivity;
import com.digitalchina.lxnsy.activity.old.PersonnelServiceListActivity;
import com.digitalchina.lxnsy.activity.old.PestDiagnosisActivity;
import com.digitalchina.lxnsy.activity.old.ProductListActivity;
import com.digitalchina.lxnsy.activity.old.RealTimePriceTabV2Activity;
import com.digitalchina.lxnsy.activity.old.TechnologyListActivity;
import com.digitalchina.lxnsy.activity.old.TechnologyTrainingVideoListActivityV2;
import com.digitalchina.lxnsy.activity.old.TrainInfoListActivity;
import com.digitalchina.lxnsy.adapter.HomePageRecyclerAdapter;
import com.digitalchina.lxnsy.api.BusinessAgricultural;
import com.digitalchina.lxnsy.api.BusinessTechnology;
import com.digitalchina.lxnsy.api.BusinessTraining;
import com.digitalchina.lxnsy.base.BaseV4Fragment;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.BannerVO;
import com.digitalchina.lxnsy.entity.HotAnswerTypeVO;
import com.digitalchina.lxnsy.entity.ServiceInfoTypeVO;
import com.digitalchina.lxnsy.entity.ServiceInfoVO;
import com.digitalchina.lxnsy.entity.TechnologyVO;
import com.digitalchina.lxnsy.entity.TrainTypeVO;
import com.digitalchina.lxnsy.entity.TrainVO;
import com.digitalchina.lxnsy.interfaces.IRecyclerType;
import com.digitalchina.lxnsy.sy.login.LoginActivity;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.JointImageUrl;
import com.digitalchina.lxnsy.xml.UserXML;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import cn.bingoogolapple.bgabanner.BGABanner;


/**
 * ================================================
 * 项目名称：BigData
 * 类描述：APP首页
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/3/24 11:53:56
 * 修改备注：
 * ================================================
 */

public class MainHomePageFragment extends BaseV4Fragment implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener, View.OnClickListener, BGABanner.Delegate<ImageView, String>, BGABanner.Adapter<ImageView, String> {

    @Bind(R.id.fragment_home_page_list_recycler_view)
    EasyRecyclerView homePageRecyclerView;

    BGABanner banner;
    TextView tvExpertConsultation;//专家咨询
    TextView tvAgriculturalForum;//农科大讲堂
    TextView tvPrice;//实时价格
    TextView tvTechnology; // 农技智库
    TextView tvPestDiagnosis; // 病虫害诊断
    TextView tvFamousInterview;//农家专访

    TextView tvTalents;//人才服务
    TextView tvTrain;//培训信息
    TextView tvStore;//农科商城
    TextView tvService;//农事服务


    private HomePageRecyclerAdapter adapter;

    private View headView;//头布局

    private List<IRecyclerType> allList = new ArrayList<>();

    private List<TrainVO> trainList = new ArrayList<>();
    private List<ServiceInfoVO> agriculturalList = new ArrayList<>();
    private List<TechnologyVO> technologyVOList = new ArrayList<>();

    private int msgWhat;

    private String productId = "";

    private List<BannerVO> bannerVOList = new ArrayList<>();

    @Override
    public View setRootView() {
        return inflate(R.layout.fragment_home_page);
    }

    @Override
    public void initMember() {

        headView = LayoutInflater.from(getActivity()).inflate(R.layout.view_headview_home_page, null);
        banner = (BGABanner) headView.findViewById(R.id.headview_home_page_banner);
        tvExpertConsultation = (TextView) headView.findViewById(R.id.headview_home_page_tv_expert_consultation);
        tvAgriculturalForum = (TextView) headView.findViewById(R.id.headview_home_page_tv_agricultural_forum);
        tvPrice = (TextView) headView.findViewById(R.id.headview_home_page_tv_price);
        tvTechnology = (TextView) headView.findViewById(R.id.headview_home_page_tv_technology);
        tvPestDiagnosis = (TextView) headView.findViewById(R.id.headview_home_page_tv_pest_diagnosis);
        tvFamousInterview = (TextView) headView.findViewById(R.id.headview_home_page_tv_famous);

        tvTalents = (TextView) headView.findViewById(R.id.headview_home_page_tv_talents);
        tvTrain = (TextView) headView.findViewById(R.id.headview_home_page_tv_train);
        tvStore = (TextView) headView.findViewById(R.id.headview_home_page_tv_store);
        tvService = (TextView) headView.findViewById(R.id.headview_home_page_tv_service);

        homePageRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//        recyclerView.addItemDecoration(Utils.setSpaceDecoration(this, false, true, false));
        adapter = new HomePageRecyclerAdapter(getActivity());

        homePageRecyclerView.setAdapter(adapter);

        adapter.addHeader(new RecyclerArrayAdapter.ItemView() {
            @Override
            public View onCreateView(ViewGroup parent) {

                return headView;
            }

            @Override
            public void onBindView(View headerView) {


            }
        });


        initBanner();
        onRefresh();

    }

    /**
     * 获取农事服务列表
     */
    public void getSerViceData() {
        BusinessAgricultural.getAgriculturalList(getActivity(), "", "", "", String.valueOf(1), String.valueOf(4), mHandler);
    }

    /**
     * 获取培训列表
     */
    public void getTrainData() {
        BusinessTraining.getTrainingByKeywords(getActivity(), "", String.valueOf(1), String.valueOf(4), mHandler);
    }

    /**
     * 获取热门回答列表(农技智库列表)
     */
    public void getTechnology() {
        BusinessTechnology.getTechnologyList(getActivity(), "", String.valueOf(1), String.valueOf(3), mHandler);
    }

    @Override
    public void addListener() {
        homePageRecyclerView.setRefreshListener(this);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                int viewType = adapter.getItem(position).type();
                if (viewType == Constant.ITEM_TYPE_SERVICE_TYPE) {//农事服务列表查看更多
                    GotoUtil.gotoActivity(getActivity(), AgriculturalServiceListActivity.class);
                } else if (viewType == Constant.ITEM_TYPE_SERVICE_LIST) {//查看农事服务详情
                    ServiceInfoVO vo = (ServiceInfoVO) adapter.getItem(position);
//                    String url = URL.SERVER + vo.getH5Url().substring(1);
                    GotoUtil.gotoActivity(getActivity(), AgriculturalServiceDetailActivity.class, false, "toServiceDetails", vo);
                } else if (viewType == Constant.ITEM_TYPE_TRAIN_TYPE) {//培训信息列表查看更多
                    GotoUtil.gotoActivity(getActivity(), TrainInfoListActivity.class);
                } else if (viewType == Constant.ITEM_TYPE_TRAIN_LIST) {//查看培训详情
                    TrainVO vo = (TrainVO) adapter.getItem(position);
                    GotoUtil.gotoActivity(getActivity(), AgriculturalTrainingDetailsActivity.class, false, "toTrainDetails", vo);
                } else if (viewType == Constant.ITEM_TYPE_HOT_ANSWER_TYPE) {//热门回答列表查看更多
                    GotoUtil.gotoActivity(getActivity(), TechnologyListActivity.class);
                } else if (viewType == Constant.ITEM_TYPE_HOT_ANSWER_LIST) {//查看热门回答详情
                    GotoUtil.gotoActivity(getActivity(), AnswerListActivity.class, "TechnologyVO", adapter.getItem(position));
                }
            }
        });

        tvExpertConsultation.setOnClickListener(this);//专家咨询
        tvAgriculturalForum.setOnClickListener(this);//农科大讲堂
        tvPrice.setOnClickListener(this);//实时价格
        tvTechnology.setOnClickListener(this);// 农技智库
        tvPestDiagnosis.setOnClickListener(this);// 病虫害诊断
        tvFamousInterview.setOnClickListener(this);//VIP服务

        tvTalents.setOnClickListener(this);//VIP服务
        tvTrain.setOnClickListener(this);//VIP服务
        tvStore.setOnClickListener(this);//VIP服务
        tvService.setOnClickListener(this);//VIP服务

        banner.setDelegate(this);


//        banner.setOnBannerListener(new OnBannerListener() {
//            @Override
//            public void OnBannerClick(int position) {
//
//                switch (position){
//                    case 0:
//                        GotoUtil.gotoActivity(getActivity(), ActivityBannerActivity.class);
//                        break;
//                    case 1:
//                        GotoUtil.gotoActivity(getActivity(), ProductListActivity.class);
//                        break;
//                }
//
//            }
//        });
//        banner.setOnBannerListener(new OnBannerListener() {
//            @Override
//            public void OnBannerClick(int position) {
//
//                if (bannerVOList == null || bannerVOList.size() <= 0)
//                    return;
//
//                Map<String,String> map = new HashMap<>();
//                /*
//                  获取首页banner
//                  0/无需跳转
//                  1/商品详情
//                  2/农事详情
//                  3/专家详情
//                  4/视频详情
//                  5/培训详情
//                  6/专访详情
//                  7/人才需求详情
//                  8/人力供应详情
//                  9/价格列表
//                  10/商品列表
//                  11/农事列表
//                  12/专家列表
//                  13/视频列表
//                  14/培训列表
//                  15/本期名家列表
//                  16/往期名家列表
//                  17/人才需求列表
//                  18/人力供应列表
//                 */
//                switch (bannerVOList.get(position).getType()) {
//                    case 0:
//
//                        break;
//                    case 1:
//                        GotoUtil.gotoActivity(getActivity(), ProductDetailActivity.class, "productId", bannerVOList.get(position).getAddressid());
//                        break;
//                    case 2:
//                        GotoUtil.gotoActivity(getActivity(), AgriculturalServiceDetailActivity.class, "bannerId", bannerVOList.get(position).getAddressid());
//                        break;
//                    case 3:
//                        GotoUtil.gotoActivity(getActivity(), AgriculturalExpertsDetailsActivity.class, "id", bannerVOList.get(position).getAddressid());
//                        break;
//                    case 4: // 视频大讲堂详情 暂时无法实现
//                        // GotoUtil.gotoActivity(getActivity(), TechnologyTrainingVideoDetailNewActivity.class, "id", bannerVOList.get(position).getAddressid());
//                        break;
//                    case 5:
//                        GotoUtil.gotoActivity(getActivity(), AgriculturalTrainingDetailsActivity.class, "JPush_attention", bannerVOList.get(position).getAddressid());
//                        break;
//                    case 6:
//                        GotoUtil.gotoActivity(getActivity(), InterviewDetailActivity.class, "bannerId", bannerVOList.get(position).getAddressid());
//                        break;
//                    case 7:
//                        map.put("bannerId",bannerVOList.get(position).getAddressid());
//                        map.put("type","0");
//                        GotoUtil.gotoActivity(getActivity(), TalentsDetailsActivity.class, "map", map);
//                        break;
//                    case 8:
//                        map.put("bannerId",bannerVOList.get(position).getAddressid());
//                        map.put("type","1");
//                        GotoUtil.gotoActivity(getActivity(), TalentsDetailsActivity.class, "map", map);
//                        break;
//                    case 9:
//                        GotoUtil.gotoActivity(getActivity(), RealTimePriceTabActivity.class);
//                        break;
//                    case 10:
//                        GotoUtil.gotoActivity(getActivity(), ProductListActivity.class);
//                        break;
//                    case 11:
//                        GotoUtil.gotoActivity(getActivity(), AgriculturalServiceListActivity.class);
//                        break;
//                    case 12:
//                        GotoUtil.gotoActivity(getActivity(), ExpertsListActivity.class);
//                        break;
//                    case 13:
//                        GotoUtil.gotoActivity(getActivity(), TechnologyTrainingVideoListActivity.class);
//                        break;
//                    case 14:
//                        GotoUtil.gotoActivity(getActivity(), TrainInfoListActivity.class);
//                        break;
//                    case 15:
//                        GotoUtil.gotoActivity(getActivity(), FamousInterviewActivity.class);
//                        break;
//                    case 16:
//                        GotoUtil.gotoActivity(getActivity(), FamousInterviewActivity.class);
//                        break;
//                    case 17:
//                        GotoUtil.gotoActivity(getActivity(), PersonnelServiceListActivity.class);
//                        break;
//                    case 18:
//                        GotoUtil.gotoActivity(getActivity(), PersonnelServiceListActivity.class);
//                        break;
//                }
//
//            }
//        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                msgWhat = msg.what;
                if (homePageRecyclerView == null) {
                    return;
                }
                if (homePageRecyclerView.getSwipeToRefresh().isRefreshing())
                    homePageRecyclerView.setRefreshing(false);
                switch (msg.what) {
                    case MSG.MSG_GET_AGRICULTURAL_SERVICE_LIST_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_AGRICULTURAL_SERVICE_LIST_FIELD:
                        showToast(msg.obj.toString());
                    case MSG.MSG_GET_TRAINING_IN_CITY_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_TRAINING_IN_CITY_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_TECHNOLOGY_LIST_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_TECHNOLOGY_LIST_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_BANNER_INFO_SUCCESS:
                        initBanner(msg.obj.toString());
                        break;
                    case MSG.MSG_BANNER_INFO_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {

        switch (msgWhat) {
            case MSG.MSG_GET_TRAINING_IN_CITY_SUCCESS://培训

                trainList = FastJsonUtil.getListBean(object.toString(), "body", "agriTrainings", TrainVO.class);

                adapter.clear();
                allList.clear();
                allList.add(new ServiceInfoTypeVO());
                if (agriculturalList != null) {
                    allList.addAll(agriculturalList);
                }
                allList.add(new TrainTypeVO());
                if (trainList != null) {
                    allList.addAll(trainList);
                }
                allList.add(new HotAnswerTypeVO());
                if (technologyVOList != null) {
                    allList.addAll(technologyVOList);
                }
                adapter.addAll(allList);

                break;
            case MSG.MSG_GET_AGRICULTURAL_SERVICE_LIST_SUCCESS://农事服务

                agriculturalList = FastJsonUtil.getListBean(object.toString(), "body", "serviceInfos", ServiceInfoVO.class);
                adapter.clear();

                allList.clear();
                allList.add(new ServiceInfoTypeVO());
                if (agriculturalList != null) {
                    allList.addAll(agriculturalList);
                }
                allList.add(new TrainTypeVO());
                if (trainList != null) {
                    allList.addAll(trainList);
                }
                allList.add(new HotAnswerTypeVO());
                if (technologyVOList != null) {
                    allList.addAll(technologyVOList);
                }
                adapter.addAll(allList);

                break;
            case MSG.MSG_TECHNOLOGY_LIST_SUCCESS://农技智库

                technologyVOList = FastJsonUtil.getListBean(object.toString(), "body", "answers", TechnologyVO.class);
                adapter.clear();

                allList.clear();
                allList.add(new ServiceInfoTypeVO());
                if (agriculturalList != null) {
                    allList.addAll(agriculturalList);
                }
                allList.add(new TrainTypeVO());
                if (trainList != null) {
                    allList.addAll(trainList);
                }
                allList.add(new HotAnswerTypeVO());
                if (technologyVOList != null) {
                    allList.addAll(technologyVOList);
                }
                adapter.addAll(allList);

                break;
        }

    }

    /**
     * 设置顶部轮播图
     */
    private void initBanner(String json) {

        List<String> imagesList = new ArrayList<>();
        List<String> titles = new ArrayList<>();
        bannerVOList = FastJsonUtil.getListBean(json, "list", BannerVO.class);
        for (int i = 0; i < bannerVOList.size(); i++) {
            imagesList.add(JointImageUrl.middleImageUrl(bannerVOList.get(i).getImg()));
            titles.add(bannerVOList.get(i).getTitle());
        }


//        //设置图片加载器
//        banner.setImageLoader(new GlideImageLoader(1));
//        //设置图片集合
//        banner.setImages(imagesList);
//        //设置标题
//        banner.setBannerTitles(titles);
//        //设置轮播时间
//        banner.setDelayTime(5000);
//        //设置风格
//        banner.setBannerStyle(BannerConfig.NOT_INDICATOR);
//        //banner设置方法全部调用完毕时最后调用
//        banner.start();

//        banner.setImages(imagesList)
//                .setBannerTitles(titles)
//                .setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE)
//                .setDelayTime(4000)
//                .setImageLoader(new GlideImageLoader(1))
//                .start();

    }

    /**
     * 设置顶部轮播图 - 本地资源
     */
    private void initBanner() {

//        List<Integer> imagesList = new ArrayList<>();
//
//        imagesList.add(R.drawable.banner000);
//        imagesList.add(R.drawable.banner0);
//        imagesList.add(R.drawable.banner1);
//        imagesList.add(R.drawable.banner2);


//        //设置图片加载器
//        banner.setImageLoader(new GlideImageLoader(1));
//        //设置图片集合
//        banner.setImages(imagesList);
//        //设置标题
//        banner.setBannerTitles(titles);
//        //设置轮播时间
//        banner.setDelayTime(5000);
//        //设置风格
//        banner.setBannerStyle(BannerConfig.NOT_INDICATOR);
//        //banner设置方法全部调用完毕时最后调用
//        banner.start();

//        banner.setImages(imagesList)
//                .setBannerStyle(BannerConfig.NUM_INDICATOR)
//                .setDelayTime(4000)
//                .setImageLoader(new GlideImageLoader(1))
//                .start();
        banner.setAdapter(this);
//        banner.setData(R.drawable.banner_1213, R.drawable.banner_1201_b, R.drawable.banner1);
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.headview_home_page_tv_expert_consultation:
                //专家咨询
                noLoginToSkip(ExpertsListActivity.class);
                break;
            case R.id.headview_home_page_tv_agricultural_forum:
                //农科大讲堂
                noLoginToSkip(TechnologyTrainingVideoListActivityV2.class);
                break;
            case R.id.headview_home_page_tv_price:
                //实时价格
                noLoginToSkip(RealTimePriceTabV2Activity.class);
//                GotoUtil.gotoActivity(getActivity(), RealTimePriceActivityNew.class);
                break;
            case R.id.headview_home_page_tv_famous:
                //农家专访修改为更多
                //首页变成两排8个
//                noLoginToSkip(FamousInterviewActivity.class);
                GotoUtil.gotoActivity(getActivity(), FamousInterviewActivity.class);
                break;
            case R.id.headview_home_page_tv_technology:
                //农技智库
                GotoUtil.gotoActivity(getActivity(), TechnologyListActivity.class);
                break;
            case R.id.headview_home_page_tv_pest_diagnosis:
                //病虫害诊断
                GotoUtil.gotoActivity(getActivity(), PestDiagnosisActivity.class);
                break;
            case R.id.headview_home_page_tv_talents:
                //人才服务-农活帮
                noLoginToSkip(PersonnelServiceListActivity.class);
//                GotoUtil.gotoActivity(getActivity(), PersonnelServiceListActivity.class);
                break;
            case R.id.headview_home_page_tv_train:
                // 2017年11月18日 11:00:07 农币商城
                GotoUtil.gotoActivity(getActivity(), CoinPresentListActivity.class);
                //培训信息 // 2017年10月31日 16:34:10 修改为 一键免费wifi
//                GotoUtil.gotoActivity(getActivity(), TrainInfoListActivity.class);
//                if (!Utils.isLogin(getActivity()))
//                    Utils.notLoginGoto(getActivity());
//                else {
//                    new MaterialDialog.Builder(getActivity())
//                            .title("提示")
//                            .content("请确定您已经打开无线局域网并且连接至\"YL-Cloud\"？")
//                            .positiveText("我已连接，继续")
//                            .negativeText("取消")
//                            .onPositive(new MaterialDialog.SingleButtonCallback() {
//                                @Override
//                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                                    GotoUtil.gotoActivity(getActivity(), OneKeyWifiActivity.class);
//                                }
//                            })
//                            .show();
//
//                }
                break;
            case R.id.headview_home_page_tv_store:
                //农科商城
                GotoUtil.gotoActivity(getActivity(), ProductListActivity.class);
                break;
            case R.id.headview_home_page_tv_service:
                //农事服务  // 2017年10月27日 13:58:18 修改为农高会专题
                GotoUtil.gotoActivity(getActivity(), AgriculturalServiceListActivity.class);
//                GotoUtil.gotoActivity(getActivity(), CafMainActivity.class);
                break;
        }
    }


    @Override
    public void onRefresh() {
        getSerViceData();
        getTrainData();
//        BusinessAccount.bannerInfo(getActivity(), mHandler);
//        getTechnology();
    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
//        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
//        banner.stopAutoPlay();
    }


    @Override
    public void onBannerItemClick(BGABanner banner, ImageView itemView, String model, int position) {
        switch (position) {
            case 0:
                noLoginToSkip(PersonnelServiceListActivity.class);
//                GotoUtil.gotoActivity(getActivity(), ActivityBannerActivity.class);
                break;
            case 1:
                GotoUtil.gotoActivity(getActivity(), CoinPresentListActivity.class);
                break;
            case 2:
                noLoginToSkip(ExpertsListActivity.class);
                break;
        }
    }

    @Override
    public void fillBannerItem(BGABanner banner, ImageView itemView, String model, int position) {
//        Glide.with(itemView.getContext())
//                .load(model)
//                .placeholder(R.drawable.bg_default)
//                .error(R.drawable.bg_default)
//                .dontAnimate()
//                .centerCrop()
//                .into(itemView);
    }

}
